<!DOCTYPE html>
<html>
<head>
  <title>OSM Buildings</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <style>
    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }

    #map {
      width: 100%;
      height: 600px;
      margin-top: 50px;
    }

    .control {
      position: absolute;
      left: 0;
      z-index: 1000;
    }

    .control.tilt {
      top: 0;
    }

    .control.rotation {
      top: 45px;
    }

    .control.zoom {
      top: 90px;
    }

    .control.zoom button {
      font-weight: normal;
    }

    .control button {
      width: 30px;
      height: 30px;
      margin: 15px 0 0 15px;
      border: 1px solid #999999;
      background: #ffffff;
      opacity: 0.6;
      border-radius: 5px;
      box-shadow: 0 0 5px #666666;
      font-weight: bold;
      text-align: center;
    }

    .control button:hover {
      opacity: 1;
      cursor: pointer;
    }
  </style>
  <link rel="stylesheet" href="../src/style.css">
  <script src="loader.js"></script>
</head>

<body>
  <!--<div id="map" style="position:absolute;top:100px"></div>-->
  <div id="map"></div>

  <div id="label" style="width:10px;height:10px;position:absolute;z-Index:1000;border:3px solid red;"></div>

  <div style="position:absolute;left:100px;top:20px;border:1px solid #ff8888; background:#fff;font-family:sans-serif;padding:10px;font-size:12px;">Click?</div>

  <div class="control tilt">
    <button class="dec">&#8601;</button>
    <button class="inc">&#8599;</button>
  </div>

  <div class="control rotation">
    <button class="inc">&#8630;</button>
    <button class="dec">&#8631;</button>
  </div>

  <div class="control zoom">
    <button class="dec">-</button>
    <button class="inc">+</button>
  </div>

  <script>
    const osmb = new OSMBuildings({
      container: 'map',
      // fastMode: true,
      attribution: '© 3D <a href="https://osmbuildings.org/copyright/">OSM Buildings</a>',
      position: { latitude:52.52000, longitude:13.41000 }, // Berlin
      // position: { latitude:53.40501, longitude:-2.96789 }, // Liverpool
      // position: { latitude:31.23638, longitude:121.49513 }, // Shanghai
      // position: { latitude:55.7528, longitude:37.62035 }, // Moscow
      // position: { latitude:40.71115, longitude:-74.01140 }, // NYC
      // position: { latitude:48.85554, longitude:2.34678 }, // Paris
      // position: { latitude: 61.50388, longitude: 23.78740 }, // Tampere

      // bounds: { n:52.52050, e:13.41050, s:52.52000, w:13.41000 },
      zoom: 20,
      rotation: 0,
      tilt: 45, // optional
      // disabled: true, // disables user input
      state: true // stores map position, zoom etc. in url
    });

    osmb.addMapTiles(
       // 'https://tile.stamen.com/toner/{z}/{x}/{y}.png',
      'https://api.mapbox.com/styles/v1/osmbuildings/cjt9gq35s09051fo7urho3m0f/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1Ijoib3NtYnVpbGRpbmdzIiwiYSI6IjNldU0tNDAifQ.c5EU_3V8b87xO24tuWil0w',
       // 'https://a.tiles.mapbox.com/v4/digitalglobe.316c9a2e/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZGlnaXRhbGdsb2JlIiwiYSI6ImNqOGRmNXltOTBucm0yd3BtY3E5czl6NmYifQ.qJJsPgCjyzMCm3YG3YWQBQ',
      {
        attribution: '© Data <a href="https://openstreetmap.org/copyright/">OpenStreetMap</a> · © Map <a href="https://mapbox.com/">Mapbox</a>'
      }
    );


    const colorByHeight = function (feature) {
      const height = parseFloat(feature.properties.height) || (parseFloat(feature.properties.levels) * 3.5) || 0;

      if (height < 20)
        feature.properties.color = "#CCCCCC";
      else if (height < 30)
        feature.properties.color = "purple";
      else if (height < 60)
        feature.properties.color = "#CC4444";
      else
        feature.properties.color = "orange";

      feature.properties.roofColor = feature.properties.color;
    };

    osmb.addGeoJSONTiles(
      // 'http://localhost:8000/0.2/dixw8kmb/tile/{z}/{x}/{y}.json',
      'https://{s}.data.osmbuildings.org/0.2/anonymous/tile/{z}/{x}/{y}.json',
      {
        fixedZoom: 15
        // bounds
      });

    //osmb.addOBJ('data/Fernsehturm.obj', { latitude:52.524133, longitude:13.407434 }, { id:'Fernsehturm', scale:2, color:'#ff0000', altitude:0, rotation:51 });
    //osmb.addOBJ('data/London Eye_MAT_LOW.obj', { latitude:51.50787, longitude:-0.12002 }, { altitude: -3, rotation:97, id:'London Eye' });

    // osmb.setPosition({ latitude:40.7484625, longitude:-73.9852667 });

    const gj = {
      type: 'FeatureCollection',
      features: [{
        type: 'Feature',
        properties: {
          color: '#ff0000',
          roofColor: '#cc0000',
          height: 50,
          minHeight: 0
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [13.37000, 52.52000],
              [13.37010, 52.52000],
              [13.37010, 52.52010],
              [13.37000, 52.52010],
              [13.37000, 52.52000]
            ]
          ]
        }
      }]
    };

    // osmb.addGeoJSON('data/test.geo.json');
    //  osmb.addGeoJSON(gj);

    //  for (let i = 0; i < 10; i++) {
    //    osmb.addOBJ('data/Zeiss Planetarium_MAT_LOW.obj?' + i, {
    //      latitude: 52.52 + (i*0.001),
    //      longitude: 13.37
    //    }, { color: '#00ccff', scale: 0.1 });
    //  }

    const label = document.getElementById('label');
    //osmb.on('change', e => {
    //    const pos = osmb.project(52.52, 13.37, 50);
    //    label.style.left = Math.round(pos.x) + 'px';
    //    label.style.top = Math.round(pos.y) + 'px';
    // });

    //   osmb.highlight(feature => {
    //     if (!feature.properties.levels && !feature.properties.height) {
    //       return 'red';
    //     }
    //     return 'green';
    //   });

    osmb.on('pointerup', e => {
      if (e.marker) {
        console.log(e.marker);
      }

      if (!e.features) {
        osmb.highlight();
        return;
      }

      const featureIDList = e.features.map(feature => feature.id);
      osmb.highlight(feature => {
        if (featureIDList.indexOf(feature.id) > -1) {
          return '#ffcc00';
        }
      });

      console.log('OSMB', e.features);

      // let query = 'https://overpass-api.de/api/interpreter?data=[out:json];(way(' + feature.id + ');relation(' + feature.id + '););out body;';

      const q = e.features.map(feature => {
        return 'way(' + feature.id + ');relation(' + feature.id + ');';
      });

      let query = 'https://overpass-api.de/api/interpreter?data=[out:json];(' + q.join('') + ');out body;';

      fetch(query)
        .then(response => response.json())
        .then(parsed => {
          console.log('Overpass', parsed.elements);
        });
    });

    //*************************************************************************

    /*
     * ## Key codes for object positioning ##
     * Cursor keys: move
     * +/- : scale
     * w/s : elevate
     * a/d : rotate
     *
     * Pressing Alt the same time accelerates
     */
    function positionOnMap(obj) {
      document.addEventListener('keydown', e => {
        let transInc = e.altKey ? 0.0002 : 0.00002;
        let scaleInc = e.altKey ? 0.1 : 0.01;
        let rotaInc = e.altKey ? 10 : 1;
        let eleInc = e.altKey ? 10 : 1;

        switch (e.keyCode) {
        case 37: obj.position.longitude -= transInc; break;
        case 39: obj.position.longitude += transInc; break;
        case 38: obj.position.latitude += transInc; break;
        case 40: obj.position.latitude -= transInc; break;
        case 187: obj.scale += scaleInc; break;
        case 189: obj.scale -= scaleInc; break;
        case 65: obj.rotation += rotaInc; break;
        case 68: obj.rotation -= rotaInc; break;
        case 87: obj.altitude += eleInc; break;
        case 83: obj.altitude -= eleInc; break;
        default: return;
        }
        console.log(JSON.stringify({
          position: {
            latitude: parseFloat(obj.position.latitude.toFixed(5)),
            longitude: parseFloat(obj.position.longitude.toFixed(5))
          },
          altitude: parseFloat(obj.altitude.toFixed(2)),
          scale: parseFloat(obj.scale.toFixed(2)),
          rotation: parseInt(obj.rotation, 10)
        }));
      });
    }

    //*************************************************************************

    if (typeof obj !== 'undefined') positionOnMap(obj);

    const controlButtons = document.querySelectorAll('.control button');

    for (let i = 0, il = controlButtons.length; i < il; i++) {
      controlButtons[i].addEventListener('click', e => {
        const button = this;
        const parentClassList = button.parentNode.classList;
        const direction = button.classList.contains('inc') ? 1 : -1;
        let increment;
        let property;

        if (parentClassList.contains('tilt')) {
          property = 'Tilt';
          increment = direction * 10;
        }
        if (parentClassList.contains('rotation')) {
          property = 'Rotation';
          increment = direction * 10;
        }
        if (parentClassList.contains('zoom')) {
          property = 'Zoom';
          increment = direction * 1;
        }
        if (property) {
          osmb['set' + property](osmb['get' + property]() + increment);
        }
      });
    }

    //***************************Marker HTML******************************

    // const marker = new osmb.Marker({ offsetY: 10}); // const marker = new osmb.Marker("OSMBuildings/marker-icon.png");
    //  marker.setPosition({latitude: 55.75025533890208, longitude: 37.61789560317993},0);
    //  marker.addToMap();
    //marker.remove();

    // for(let i = 0;i< 150; i++ ){
    //   let temp = new osmb.Marker();
    //   temp.setPosition({latitude: 55.751 + Math.random()/100 , longitude: 37.617 + Math.random()/100},0);
    //   //temp.setPosition({latitude: 5+ Math.random() , longitude: 37 + Math.random()},0);
    //   temp.addToMap();
    //   // temp.addEventListener('click', (e) => console.log("clicked"));
    //   // temp.removeEventListener('click', (e) => console.log("clicked"));
    // }

    //***************************Marker WebGL**********************************

    // let marker = osmb.addMarker({ latitude: 55.75079, longitude: 37.61828, altitude: 75 },
    //   { id: 1 },
    //   {
    //     // url: 'star-icon.svg',
    //     url: 'k+p.svg',
    //     color: 'rgb(0,60,100)'
    //   });

    let marker2 = osmb.addMarker({ latitude: 55.75000, longitude: 37.61808, altitude: 5 },
      { payload: [] });

  // // osmb.remove(marker); // will not work too early

    for (let i = 0;i< 15; i++) {
      osmb.addMarker({ latitude: 55.751 + Math.random()/100, longitude: 37.617 + Math.random()/100, altitude: 10 + Math.random()*50 }, { index: i }, { color: 'rgb(0,60,100)' });
    }

  </script>
</body>
</html>
